/*
 * @Author: Janssen000908 2601566046@qq.com
 * @Date: 2025-05-07 20:29:33
 * @LastEditors: Janssen000908 2601566046@qq.com
 * @LastEditTime: 2025-05-07 20:29:33
 * @FilePath: /learn39/mycond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;

int cnt = 0;
pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t _cond = PTHREAD_COND_INITIALIZER;

void* Count(void* args)
{
    pthread_detach(pthread_self()); // 将自己分离：非阻塞回收

    uint64_t number = (uint64_t)args; //uint4_t无符号长整形
    while(true)
    {
        cout << "pthread: " << number << "thread created "<<endl;

        pthread_mutex_lock(&_mutex);
        pthread_cond_wait(&_cond,&_mutex);//每个线程先去等待队列等待
        pthread_mutex_unlock(&_mutex);
    }
}
int main()
{
    for(uint64_t i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);//传入&i可能会导致子线程修改原始数据i，所以选择值传递
        usleep(1000);
    }

    sleep(3);
    cout << "main thread begin...." << endl;
    cout << "main thread begin...." << endl;

    //使用主线程来按需唤醒线程
    while(true)
    {   //每隔一秒唤醒一个线程
        sleep(1);
        pthread_cond_signal(&_cond);//默认唤醒等待队列中的第一个线程
        cout << "signal one thread...." <<endl;
    }
    while(true) sleep(1);
    return 0;
}